import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'

// 布局组件 - 懒加载
const Layout = () => import('@/layouts/index.vue')

/**
 * 静态路由 - 无需权限
 */
export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/403',
    name: '403',
    component: () => import('@/views/error-page/403.vue'),
    meta: { title: '403', hidden: true }
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error-page/404.vue'),
    meta: { title: '404', hidden: true }
  }
  ,
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '控制台' }
      }
    ]
  }
]
export const asyncRoutes = [
  // {
  //   path: '/statistics',
  //   component: Layout,
  //   redirect: '/statistics/sales-analysis',
  //   meta: { title: '数据统计', icon: 'PieChart' },
  //   children: [
  //     {
  //       path: 'sales-analysis',
  //       name: 'SalesAnalysis',
  //       component: () => import('@/views/statistics/SalesAnalysis.vue'),
  //       meta: { title: '销售分析', icon: 'TrendCharts' }
  //     }
  //   ]
  // },
  {
    path: '/sales-ranking',
    component: Layout,
    redirect: '/sales-ranking/index',
    meta: { title: '销量排行榜', icon: 'Trophy', permission: 'system', icon: 'Setting' },
    children: [
      {
        path: 'index',
        name: 'SalesRanking',
        component: () => import('@/views/agent/sales-ranking.vue'),
        meta: { title: '今日销量排行榜', icon: 'TrendCharts' }
      }
    ]
  },
  {
    path: '/user',
    component: Layout,
    redirect: '/user/list',
    meta: { title: '用户管理', icon: 'User' },
    children: [
      {
        path: 'list',
        name: 'UserList',
        component: () => import('@/views/user/list.vue'),
        meta: { title: '用户列表', icon: 'UserFilled' }
      },
      {
        path: 'edit/:id',
        name: 'UserEdit',
        component: () => import('@/views/user/edit.vue'),
        meta: { title: '编辑用户', hidden: true, icon: 'Edit' }
      }
    ]
  },
  {
    path: '/agent',
    component: Layout,
    redirect: '/agent/list',
    meta: { title: '代理管理', icon: 'Connection' },
    children: [
      {
        path: 'list',
        name: 'AgentList',
        component: () => import('@/views/agent/list.vue'),
        meta: { title: '代理列表', icon: 'User' }
      },
      {
        path: 'tree',
        name: 'AgentTree',
        component: () => import('@/views/agent/tree.vue'),
        meta: { title: '代理结构', icon: 'Share' }
      },
      {
        path: 'commission',
        name: 'AgentCommission',
        component: () => import('@/views/agent/commission.vue'),
        meta: { title: '佣金管理', icon: 'Coin' }
      },

      {
        path: 'detail/:id',
        name: 'AgentDetail',
        component: () => import('@/views/agent/detail.vue'),
        meta: { title: '代理详情', hidden: true, icon: 'InfoFilled' }
      },
      {
        path: 'edit/:id',
        name: 'AgentEdit',
        component: () => import('@/views/agent/edit.vue'),
        meta: { title: '编辑代理', hidden: true, icon: 'Edit' }
      }
    ]
  },
  {
    path: '/account',
    component: Layout,
    redirect: '/account/list',
    meta: { title: '分销管理', icon: 'Wallet' },
    children: [
      {
        path: 'list',
        name: 'AccountList',
        component: () => import('@/views/account/index.vue'),
        meta: { title: '账号明细', icon: 'Document' }
      }
    ]
  },
  {
    path: '/order',
    component: Layout,
    redirect: '/order/list',
    meta: { title: '订单管理', icon: 'List' },
    children: [
      {
        path: 'list',
        name: 'OrderList',
        component: () => import('@/views/order/list.vue'),
        meta: { title: '订单列表', icon: 'List' }
      },
      {
        path: 'detail/:id',
        name: 'OrderDetail',
        component: () => import('@/views/order/detail.vue'),
        meta: { title: '订单详情', hidden: true, icon: 'InfoFilled' }
      }
    ]
  },
  {
    path: '/withdraw',
    component: Layout,
    redirect: '/withdraw/list',
    meta: { title: '提现管理', icon: 'Money' },
    children: [
      {
        path: 'list',
        name: 'Withdraw',
        component: () => import('@/views/withdraw/list.vue'),
        meta: { title: '提现管理', icon: 'Money' }
      }
    ]
  },
  {
    path: '/recognition',
    component: Layout,
    redirect: '/recognition/list',
    meta: { title: '识别记录', icon: 'Histogram' },
    children: [
      {
        path: 'list',
        name: 'RecognitionList',
        component: () => import('@/views/recognition/list.vue'),
        meta: { title: '记录列表', icon: 'Document' }
      },
      {
        path: 'detail/:id',
        name: 'RecognitionDetail',
        component: () => import('@/views/recognition/detail.vue'),
        meta: { title: '记录详情', hidden: true, icon: 'InfoFilled' }
      },
      {
        path: 'statistics',
        name: 'RecognitionStatistics',
        component: () => import('@/views/recognition/statistics.vue'),
        meta: { title: '统计分析', icon: 'PieChart' }
      }
    ]
  },
  {
    path: '/plan',
    component: Layout,
    redirect: '/plan/list',
    meta: { title: '套餐管理', icon: 'Box' },
    children: [
      {
        path: 'list',
        name: 'PlanList',
        component: () => import('@/views/plan/list.vue'),
        meta: { title: '套餐列表', icon: 'Box' }
      },
      {
        path: 'edit/:id',
        name: 'PlanEdit',
        component: () => import('@/views/plan/edit.vue'),
        meta: { title: '编辑套餐', hidden: true, icon: 'Edit' }
      },
      {
        path: 'add',
        name: 'PlanAdd',
        component: () => import('@/views/plan/add.vue'),
        meta: { title: '添加套餐', icon: 'Plus' }
      }
    ]
  },
  {
    path: '/article',
    component: Layout,
    redirect: '/article/list',
    meta: { title: '文章管理', icon: 'Document' },
    children: [
      {
        path: 'list',
        name: 'ArticleList',
        component: () => import('@/views/article/list.vue'),
        meta: { title: '文章列表', icon: 'Document' }
      },
      {
        path: 'edit/:id',
        name: 'ArticleEdit',
        component: () => import('@/views/article/edit.vue'),
        meta: { title: '编辑文章', hidden: true, icon: 'Edit' }
      },
      {
        path: 'add',
        name: 'ArticleAdd',
        component: () => import('@/views/article/add.vue'),
        meta: { title: '添加文章', icon: 'Plus' }
      }
    ]
  },
  {
    path: '/notice',
    component: Layout,
    redirect: '/notice/list',
    meta: { title: '公告管理', icon: 'Bell' },
    children: [
      {
        path: 'list',
        name: 'NoticeList',
        component: () => import('@/views/notice/list.vue'),
        meta: { title: '公告列表', icon: 'Bell' }
      },
      {
        path: 'edit/:id',
        name: 'NoticeEdit',
        component: () => import('@/views/notice/edit.vue'),
        meta: { title: '编辑公告', hidden: true, icon: 'Edit' }
      },
      {
        path: 'add',
        name: 'NoticeAdd',
        component: () => import('@/views/notice/add.vue'),
        meta: { title: '添加公告', icon: 'Plus' }
      }
    ]
  },
  {
    path: '/banner',
    component: Layout,
    redirect: '/banner/list',
    meta: { title: '轮播图管理', icon: 'Picture' },
    children: [
      {
        path: 'list',
        name: 'BannerList',
        component: () => import('@/views/banner/list.vue'),
        meta: { title: '轮播图列表', icon: 'Picture' }
      },
      {
        path: 'edit/:id',
        name: 'BannerEdit',
        component: () => import('@/views/banner/edit.vue'),
        meta: { title: '编辑轮播图', hidden: true, icon: 'Edit' }
      },
      {
        path: 'add',
        name: 'BannerAdd',
        component: () => import('@/views/banner/add.vue'),
        meta: { title: '添加轮播图', icon: 'Plus' }
      }
    ]
  },
  {
    path: '/feedback',
    component: Layout,
    redirect: '/feedback/list',
    meta: { title: '反馈管理', icon: 'ChatLineRound' },
    children: [
      {
        path: 'list',
        name: 'FeedbackList',
        component: () => import('@/views/feedback/list.vue'),
        meta: { title: '反馈列表', icon: 'ChatLineRound' }
      },
      {
        path: 'detail/:id',
        name: 'FeedbackDetail',
        component: () => import('@/views/feedback/detail.vue'),
        meta: { title: '反馈详情', hidden: true, icon: 'InfoFilled' }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    redirect: '/system/roles',
    meta: { title: '系统管理', permission: 'system', icon: 'Setting' },
    children: [
      {
        path: 'roles',
        name: 'RoleList',
        component: () => import('@/views/system/roles/index.vue'),
        meta: { title: '角色管理', permission: 'view:role', icon: 'User' }
      },
      {
        path: 'roles/create',
        name: 'RoleCreate',
        component: () => import('@/views/system/roles/create.vue'),
        meta: { title: '创建角色', hidden: true, permission: 'add:role', icon: 'Plus' }
      },
      {
        path: 'roles/edit/:id',
        name: 'RoleEdit',
        component: () => import('@/views/system/roles/edit.vue'),
        meta: { title: '编辑角色', hidden: true, permission: 'edit:role', icon: 'Edit' }
      },
      {
        path: 'users',
        name: 'UserManage',
        component: () => import('@/views/system/users/index.vue'),
        meta: { title: '用户管理', permission: 'view:user', icon: 'User' }
      },
      // {
      //   path: 'admins',
      //   name: 'AdminManage',
      //   component: () => import('@/views/system/admins/index.vue'),
      //   meta: { title: '管理员管理', permission: 'view:admin', icon: 'UserFilled' }
      // },
      {
        path: 'menus',
        name: 'MenuManage',
        component: () => import('@/views/system/menus/index.vue'),
        meta: { title: '菜单管理', permission: 'view:menu', icon: 'Menu' }
      },
      // {
      //   path: 'tenants',
      //   name: 'TenantManage',
      //   component: () => import('@/views/system/tenants/index.vue'),
      //   meta: { title: '租户管理', permission: 'view:tenant', icon: 'OfficeBuilding' }
      // },
      {
        path: 'permissions',
        name: 'PermissionManage',
        component: () => import('@/views/system/permissions/index.vue'),
        meta: { title: '权限管理', permission: 'view:permission', icon: 'Lock' }
      }
      // ,
      // {
      //   path: 'privacy-editor',
      //   name: 'PrivacyPolicyEditor',
      //   component: () => import('@/views/system/PrivacyEditor/index.vue'),
      //   meta: { title: '隐私协议管理', permission: 'view:privacy_policy', icon: 'Document' }
      // }
    ]
  },
  {
    path: '/core',
    component: Layout,
    redirect: '/core/dict-core',
    meta: { title: '系统配置', icon: 'Setting' },
    children: [
      {
        path: 'dict-core',
        name: 'DictConfig',
        component: () => import('@/views/config/list.vue'),
        meta: { title: '字典配置', icon: 'Notebook' }
      }
      // ,
      // {
      //   path: 'tenant-configs',
      //   name: 'TenantConfigs',
      //   component: () => import('@/views/system/tenant-configs.vue'),
      //   meta: { title: '租户配置', icon: 'Tools' }
      // }
    ]
  },
  {
    path: '/activation-code',
    component: Layout,
    redirect: '/activation-code/list',
    meta: { title: '激活码管理', icon: 'Key' },
    children: [
      {
        path: 'list',
        name: 'ActivationCodeList',
        component: () => import('@/views/activation-code/list.vue'),
        meta: { title: '激活码列表', icon: 'Key' }
      },
      {
        path: 'generate',
        name: 'ActivationCodeGenerate',
        component: () => import('@/views/activation-code/generate.vue'),
        meta: {
          title: '生成激活码',
          icon: 'Plus'
        }
      }
    ]
  },
  {
    path: '/log',
    component: Layout,
    redirect: '/log/list',
    meta: { title: '日志管理', icon: 'DocumentCopy' },
    children: [
      {
        path: 'list',
        name: 'LogList',
        component: () => import('@/views/log/list.vue'),
        meta: { title: '操作日志', icon: 'DocumentCopy' }
      }
    ]
  },
  {
    path: '/img-upload',
    component: Layout,
    redirect: '/img-upload/list',
    meta: { title: '图片上传', icon: 'UploadFilled' },
    children: [
      {
        path: 'list',
        name: 'ImgUploadList',
        component: () => import('@/views/img-upload/index.vue'),
        meta: { title: '图片上传', icon: 'UploadFilled' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
    hidden: true
  }
]


const allRoutes = [...constantRoutes]

const router = createRouter({
  history: createWebHashHistory(),
  routes: allRoutes
})

// 判断是否已添加动态路由
let dynamicRoutesAdded = false

// 重置路由
export function resetRouter() {
  // 重置路由
  const newRouter = createRouter({
    history: createWebHashHistory(),
    routes: constantRoutes
  })

  // 替换现有路由
  router.matcher = newRouter.matcher

  // 重置标记
  dynamicRoutesAdded = false
}

// 根据权限过滤路由
export function filterAsyncRoutes(routes, permissions) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }

    // 如果当前路由需要权限，则检查用户是否有该权限
    if (tmp.meta && tmp.meta.permission) {
      const hasPermission = permissions.includes(tmp.meta.permission)
      if (!hasPermission) return
    }

    // 如果有子路由，则递归过滤
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children, permissions)
      // 如果过滤后没有子路由，且当前路由也没有组件，则跳过
      if (tmp.children.length === 0 && !tmp.component) {
        return
      }
    }

    res.push(tmp)
  })

  return res
}

// 动态添加路由
export async function addRoutes() {
  if (dynamicRoutesAdded) return

  const userStore = useUserStore()

  // 直接检查是否是管理员，如果是，直接添加所有路由
  if (userStore.isAdmin) {
    asyncRoutes.forEach(route => {
      router.addRoute(route)
    })
    dynamicRoutesAdded = true
    return
  }

  // 如果用户有权限，则动态添加路由
  if (userStore.permissions && userStore.permissions.length > 0) {
    // 根据权限过滤路由
    const accessRoutes = filterAsyncRoutes(asyncRoutes, userStore.permissions)
    accessRoutes.forEach(route => {
      router.addRoute(route)
    })

    dynamicRoutesAdded = true
  }
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title || '管理系统'} - 题库`

  const userStore = useUserStore()
  const token = userStore.token

  console.log('Router guard activated:', {
    to: to.path,
    from: from.path,
    token: !!token,
    permissions: userStore.permissions,
    username: userStore.name
  })

  if (to.path === '/login') {
    if (token) {
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    if (!token) {
      next(`/login?redirect=${to.path}`)
    } else {
      // 特殊处理test_admin用户，直接允许访问所有页面
      if (userStore.name === 'test_admin') {
        console.log('Test admin detected, granting access')

        // 确保已添加动态路由
        if (!dynamicRoutesAdded) {
          asyncRoutes.forEach(route => {
            router.addRoute(route)
          })
          dynamicRoutesAdded = true

          // 确保导航到正确路径
          next({ ...to, replace: true })
        } else {
          next()
        }
        return
      }

      // 普通测试账号特殊处理 - 检查是否要访问的页面是只读页面
      if (userStore.isTest) {
        console.log('Test account detected, restricting access to view-only')

        // 检查当前路由是否被testRestricted标记
        if (to.meta && to.meta.testRestricted === true) {
          console.warn('测试账号试图访问受限页面:', to.path)
          ElMessage.error('测试账号无权访问此页面')
          next('/dashboard')
          return
        }

        // 非view页面只允许访问dashboard和list页面
        const isViewRoute = to.path.includes('/dashboard') ||
          to.path.includes('/list') ||
          to.path.includes('/view') ||
          to.path === '/';

        // 如果目标路由包含add/edit/delete等关键字，重定向到dashboard
        if (!isViewRoute && (
          to.path.includes('/add') ||
          to.path.includes('/create') ||
          to.path.includes('/edit') ||
          to.path.includes('/delete')
        )) {
          console.warn('测试账号尝试访问非查看页面，重定向到dashboard')
          next('/dashboard')
          return
        }

        // 确保已添加动态路由
        if (!dynamicRoutesAdded) {
          asyncRoutes.forEach(route => {
            router.addRoute(route)
          })
          dynamicRoutesAdded = true
        }

        next()
        return
      }

      // 获取用户信息和权限
      if (!userStore.permissions || userStore.permissions.length === 0) {
        try {
          // 获取用户信息，包括用户权限
          await userStore.getInfoAction()

          // 根据用户权限动态添加路由
          await addRoutes()

          // 确保添加了路由
          next({ ...to, replace: true })
        } catch (error) {
          // 获取用户信息失败，可能是token过期
          console.error('获取用户信息失败:', error)
          userStore.resetState()
          next(`/login?redirect=${to.path}`)
        }
      } else {
        // 如果有权限要求，则检查是否有权限访问
        if (to.meta && to.meta.permission) {
          if (userStore.hasPermission(to.meta.permission)) {
            next()
          } else {
            console.warn(`用户 ${userStore.name} 没有权限访问 ${to.path}, 需要权限: ${to.meta.permission}`)
            next('/403')
          }
        } else {
          next()
        }
      }
    }
  }
})

export default router